package com.group4.datafactorybackend.service.impl;

import cn.hutool.http.Header;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group4.datafactorybackend.common.DataFactoryConstantPool;
import com.group4.datafactorybackend.common.R;
import com.group4.datafactorybackend.common.enums.MyEnumClass;
import com.group4.datafactorybackend.common.enums.ResultCodeEnum;
import com.group4.datafactorybackend.common.exception.DataFactoryException;
import com.group4.datafactorybackend.entity.DO.*;
import com.group4.datafactorybackend.entity.DTO.*;
import com.group4.datafactorybackend.entity.VO.ApiDetailVO;
import com.group4.datafactorybackend.entity.VO.ApiParamterVO;
import com.group4.datafactorybackend.mapper.*;
import com.group4.datafactorybackend.service.ApcStopwatchService;
import com.group4.datafactorybackend.service.ApiParamterConfigurationService;
import com.group4.datafactorybackend.service.ApiService;
import com.group4.datafactorybackend.service.StopwatchManagementService;
import com.group4.datafactorybackend.util.CodeUtil;
import com.group4.datafactorybackend.util.HttpRequestUtils;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 *  @author 邹代鑫
 *  @date 2022/8/10
 *  @description
*/
@Service
public class ApiServiceImpl extends ServiceImpl<ApiMapper, ApiDO> implements ApiService{

    @Autowired
    private ApiMapper apiMapper;

    @Autowired
    private ApiParamterConfigurationMapper apiParamterConfigurationMapper;

    @Autowired
    private ApcStopwatchMapper apcStopwatchMapper;

    @Autowired
    private ApiParamterConfigurationService apiParamterConfigurationService;

    @Autowired
    private ApcStopwatchService apcStopwatchService;

    @Autowired
    private DirectoryServiceImpl directoryService;

    @Autowired
    private DirectoryMapper directoryMapper;

    @Autowired
    private StopwatchManagementService stopwatchManagementService;

    @Autowired
    private StopwatchManagementMapper stopwatchManagementMapper;

    /**
     * @author 李泓静
     * @param apiCode 接口编号
     * @return R
     * @description 查看接口详情
     */
   @Override
   public R<?> getApiDetail(String apiCode){
       //查询接口基本信息
       LambdaQueryWrapper<ApiDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
       lambdaQueryWrapper.eq(ApiDO::getApiCode,apiCode);
       ApiDO apiDO = apiMapper.selectOne(lambdaQueryWrapper);
       //将结果复制给vo
       ApiDetailVO createUpdateApiDetailVO = new ApiDetailVO();
       BeanUtils.copyProperties(apiDO,createUpdateApiDetailVO);

       //将查询的接口参数配置信息列表放入接口详情
       List<ApiParamterVO> apiParamterList = getApiParamterConfigurationList(apiCode);

       List<ApiParamterVO> paramList = new ArrayList<>();
       List<ApiParamterVO> bodyList = new ArrayList<>();
       List<ApiParamterVO> resultList = new ArrayList<>();
       //遍历结果集合分配给不同位置
       for (ApiParamterVO apiParamter : apiParamterList) {
           if (MyEnumClass.ApiParamPositionEnum.PARAM_POSITION_QUERY.getCode().equals(apiParamter.getApcPosition())) {
               paramList.add(apiParamter);
           }
           if (MyEnumClass.ApiParamPositionEnum.PARAM_POSITION_HEADER.getCode().equals(apiParamter.getApcPosition())) {
               paramList.add(apiParamter);
           }
           if (MyEnumClass.ApiParamPositionEnum.PARAM_POSITION_BODY.getCode().equals(apiParamter.getApcPosition())) {
               bodyList.add(apiParamter);
           }
           if (MyEnumClass.ApiParamPositionEnum.PARAM_POSITION_QUERY.getCode().equals(apiParamter.getApcPosition())) {
               resultList.add(apiParamter);
           }
       }
       createUpdateApiDetailVO.setParamList(paramList);
       createUpdateApiDetailVO.setBodyList(bodyList);
       createUpdateApiDetailVO.setResultList(resultList);
       return R.Success(ResultCodeEnum.SUCCESS, createUpdateApiDetailVO);
    }

    /**
     * @author 邹代鑫
     * @param createOrUpdateApiDTO 新增、修改接口接收参数实体类
     * @return R
     * @description 新增接口
     */
   @Override
   @Transactional(rollbackFor = Exception.class)
   public R<?> createOrUpdateApi(CreateOrUpdateApiDTO createOrUpdateApiDTO) {
       // 调用数据校验方法
       R<?> result = this.verifyApiData(createOrUpdateApiDTO);
       if (ResultCodeEnum.DATA_EXIST.getCode().equals(result.getCode())) {
           return result;
       }

       ApiDO api = new ApiDO();
       BeanUtils.copyProperties(createOrUpdateApiDTO, api);
       if (StringUtils.isBlank(api.getApiCode())) {
           api.setApiCode(CodeUtil.getCode());
           api.setApiStatus(MyEnumClass.StatusEnum.NOT_RELEASE.getCode());
       }else {
           // 判断是新增还是编辑
           LambdaQueryWrapper<ApiDO> queryWrapper = new LambdaQueryWrapper<>();
           queryWrapper.eq(ApiDO::getApiCode, api.getApiCode());
           int count = apiMapper.selectCount(queryWrapper);
           if (count <= 0) {
               return R.Failed(ResultCodeEnum.OPERATION_FAILED.getCode(),"编辑的数据不存在",false);
           }
       }
       try {
           // 插入接口参数配置信息（如果接口参数配置信息不为空就执行）
           if (ObjectUtils.isNotEmpty(createOrUpdateApiDTO.getCreateOrUpdateApiParamterConfigurationList())) {
               // 查询该接口下的所有引用了码表的接口配置编号
               List<String> apcCodeList = apiParamterConfigurationMapper.getHasStopwatchQuoteApiParamterConfigurationCodeList(api.getApiCode());
               for (String apcCode : apcCodeList) {
                   // 删除所有引用关系
                   LambdaQueryWrapper<ApcStopwatchDO> deleteApcStopwatchWrapper = new LambdaQueryWrapper<>();
                   deleteApcStopwatchWrapper.eq(ApcStopwatchDO::getApcCode, apcCode);
                   apcStopwatchMapper.delete(deleteApcStopwatchWrapper);
               }
               // 清空该接口下已存在的接口参数配置
               LambdaQueryWrapper<ApiParamterConfigurationDO> deleteWrapper = new LambdaQueryWrapper<>();
               deleteWrapper.eq(ApiParamterConfigurationDO::getApiCode, api.getApiCode());
               apiParamterConfigurationMapper.delete(deleteWrapper);
               // 调用递归方法，替换UUID，并将数据扁平化处理
               List<CreateOrUpdateApiParamterConfigurationDTO> apiParamterConfigurationDtoList = new ArrayList<>();
               changeCodeAndFlat(api.getApiCode(), api.getApiCode(), createOrUpdateApiDTO.getCreateOrUpdateApiParamterConfigurationList(), apiParamterConfigurationDtoList);

               // 新增引用关系对象集合
               List<ApcStopwatchDO> apcStopwatchList = new ArrayList<>();
               // 新增接口参数配置对象集合
               List<ApiParamterConfigurationDO> apiParamterConfigurationDoList = new ArrayList<>();
               for (CreateOrUpdateApiParamterConfigurationDTO createOrUpdateApiParamterConfiguration : apiParamterConfigurationDtoList) {
                   // 新增码表信息
                   // 当数据类型为Int或Float，且传入的码表对象不为空时才进行码表引用
                   Integer dataTypeCode = createOrUpdateApiParamterConfiguration.getApcDataType();
                   Integer intCode = MyEnumClass.DataTypeEnum.DATA_TYPE_INT.getCode();
                   Integer floatCode = MyEnumClass.DataTypeEnum.DATA_TYPE_FLOAT.getCode();
                   if (intCode.equals(dataTypeCode) || floatCode.equals(dataTypeCode)) {
                       // 判断如果传入的码表对象为空，则表示此条接口配置信息不需要引用码表，进行下一次循环
                       if (ObjectUtils.isEmpty(createOrUpdateApiParamterConfiguration.getCreateOrUpdateStopwatch())) {
                           continue;
                       }
                       // 判断当前码表是否已存在，不存在则新增，存在则直接引用（通过传入码表编号是否为空判断，新增为空，引用不为空）
                       if (StringUtils.isBlank(createOrUpdateApiParamterConfiguration.getCreateOrUpdateStopwatch().getStopwatchCode())) {
                           // 传入码表编号为空，表示需要新增码表
                           R<?> addStopwatchResult = stopwatchManagementService.addStopwatch(createOrUpdateApiParamterConfiguration.getCreateOrUpdateStopwatch());
                           // 获取新增的码表编号
                           String stopwatchCode = (String) addStopwatchResult.getData();
                           createOrUpdateApiParamterConfiguration.getCreateOrUpdateStopwatch().setStopwatchCode(stopwatchCode);
                       } else {
                           // 传入码表编号不为空，表示直接引用码表，此时需要判断引用的码表数据库是否存在
                           LambdaQueryWrapper<StopwatchDO> queryStopwatchWrapper = new LambdaQueryWrapper<>();
                           queryStopwatchWrapper.eq(StopwatchDO::getStopwatchCode, createOrUpdateApiParamterConfiguration.getCreateOrUpdateStopwatch().getStopwatchCode());
                           StopwatchDO stopwatch = stopwatchManagementMapper.selectOne(queryStopwatchWrapper);
                           if (ObjectUtils.isEmpty(stopwatch)) {
                               throw new DataFactoryException("引用码表不存在");
                           }
                       }
                       // 收集引用关系对像
                       ApcStopwatchDO apcStopwatch = new ApcStopwatchDO();
                       apcStopwatch.setApcCode(createOrUpdateApiParamterConfiguration.getApcCode());
                       apcStopwatch.setStopwatchCode(createOrUpdateApiParamterConfiguration.getCreateOrUpdateStopwatch().getStopwatchCode());
                       apcStopwatchList.add(apcStopwatch);
                   }

                   // 收集接口参数配置对象
                   ApiParamterConfigurationDO apiParamterConfiguration = new ApiParamterConfigurationDO();
                   BeanUtils.copyProperties(createOrUpdateApiParamterConfiguration, apiParamterConfiguration);
                   apiParamterConfigurationDoList.add(apiParamterConfiguration);
               }
               // 批量新增接口参数配置
               apiParamterConfigurationService.saveBatch(apiParamterConfigurationDoList);
               // 批量添加接口参数引用关系
               apcStopwatchService.saveBatch(apcStopwatchList);
           }
           // 新增或修改接口信息
           boolean bool = this.saveOrUpdate(api);
           if (!bool) {
               throw new DataFactoryException(ResultCodeEnum.OPERATION_FAILED.getMessage());
           }
           return R.Success(ResultCodeEnum.OPERATION_SUCCESS, true);
       } catch (Exception e) {
           e.printStackTrace();
           return R.Failed(ResultCodeEnum.OPERATION_FAILED.getCode(), e.getMessage(), false);
       }
   }

    /**
     * @author 卑微小峰
     * @param parentCode 父级参数编号
     * @param apiCode 接口编号
     * @param childrenList 树结构集合
     * @param apiParamterConfigurationList 替换编号、扁平化处理后返回对象集合
     * @return List
     * @description 替换编号、扁平化处理树对象
     */
   private List<CreateOrUpdateApiParamterConfigurationDTO> changeCodeAndFlat(String parentCode, String apiCode, List<CreateOrUpdateApiParamterConfigurationDTO> childrenList, List<CreateOrUpdateApiParamterConfigurationDTO> apiParamterConfigurationList) {
       for (CreateOrUpdateApiParamterConfigurationDTO children : childrenList) {
           // 替换接口参数配置编号
           children.setApcCode(CodeUtil.getCode());
           // 替换接口参数配置父级编号
           children.setApcParentParamCode(parentCode);
           // 替换接口参数配置中的接口编号
           children.setApiCode(apiCode);
           // 数据扁平化处理
           apiParamterConfigurationList.add(children);
           // 递归调用
           if (ObjectUtils.isNotEmpty(children.getChildrenList())) {
               changeCodeAndFlat(children.getApcCode(), apiCode, children.getChildrenList(), apiParamterConfigurationList);
           }
       }
       return apiParamterConfigurationList;
   }

    /**
     * @author 卑微小峰
     * @param batchReleaseOrOutageDTO （批量）发布/停用接收参数实体类
     * @return R
     * @description (批量)发布/停用接口
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> releaseOrOutage(BatchReleaseOrOutageDTO batchReleaseOrOutageDTO) {
        Integer apiStatus = batchReleaseOrOutageDTO.getStatus();
        List<String> apiCodeList = batchReleaseOrOutageDTO.getCodeList();

        // 判断批量（停用）操作的接口中是否存在未发布状态
        if (apiStatus.equals(MyEnumClass.StatusEnum.HAVE_DISABLE.getCode())) {
            LambdaQueryWrapper<ApiDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ApiDO::getApiStatus, MyEnumClass.StatusEnum.NOT_RELEASE.getCode())
                    .in(ApiDO::getApiCode, apiCodeList);
            int result = apiMapper.selectCount(lambdaQueryWrapper);
            if (result > 0) {
                return R.Failed(ResultCodeEnum.EXIST_NOT_RELEASE.getCode(), "存在未发布的接口");
            }
        }
        // 判断批量（发布）操作的接口中是否存在已发布状态
        if (apiStatus.equals(MyEnumClass.StatusEnum.HAVE_RELEASE.getCode())) {
            LambdaQueryWrapper<ApiDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ApiDO::getApiStatus, MyEnumClass.StatusEnum.HAVE_RELEASE.getCode())
                    .in(ApiDO::getApiCode, apiCodeList);
            int result = apiMapper.selectCount(lambdaQueryWrapper);
            if (result > 0) {
                return R.Failed(ResultCodeEnum.EXIST_HAVE_RELEASE.getCode(), "存在已发布的接口");
            }
        }

        try {
            for (String apiCode : apiCodeList) {
                // 查询此接口编号下的所有含有码值定义的接口配置编号
                List<String> apcCodeList = apiParamterConfigurationMapper.getHasStopwatchQuoteApiParamterConfigurationCodeList(apiCode);

                // 存在含有码值定义的接口参数配置，先开启（关闭）引用，再修改发布状态
                if (apcCodeList.size() > 0) {
                    LambdaUpdateWrapper<ApcStopwatchDO> updateQuoteStopwatchStatusWrapper = new LambdaUpdateWrapper<>();
                    if (apiStatus.equals(MyEnumClass.StatusEnum.HAVE_RELEASE.getCode())) {
                        updateQuoteStopwatchStatusWrapper.in(ApcStopwatchDO::getApcCode,apcCodeList)
                                .set(ApcStopwatchDO::getIsDisable, MyEnumClass.QuoteStatusEnum.OPEN_QUOTE.getCode());
                        apcStopwatchMapper.update(null, updateQuoteStopwatchStatusWrapper);
                    }else if (apiStatus.equals(MyEnumClass.StatusEnum.HAVE_DISABLE.getCode())) {
                        updateQuoteStopwatchStatusWrapper.in(ApcStopwatchDO::getApcCode,apcCodeList)
                                .set(ApcStopwatchDO::getIsDisable, MyEnumClass.QuoteStatusEnum.CLOSE_QUOTE.getCode());
                        apcStopwatchMapper.update(null,updateQuoteStopwatchStatusWrapper);
                    }else {
                        return R.Failed("错误的状态值");
                    }
                }
            }
            // 修改接口状态
            LambdaUpdateWrapper<ApiDO> releaseOrOutageWrapper = new LambdaUpdateWrapper<>();
            releaseOrOutageWrapper.in(ApiDO::getApiCode,apiCodeList)
                    .set(ApiDO::getApiStatus,apiStatus);
            int result = apiMapper.update(null,releaseOrOutageWrapper);
            if (result <= 0) {
                return R.Failed(ResultCodeEnum.OPERATION_FAILED);
            }
        } catch (Exception e) {
            return R.Failed(ResultCodeEnum.OPERATION_FAILED);
        }
        return R.Success(ResultCodeEnum.OPERATION_SUCCESS);
    }

    /**
     * @author 卑微小峰
     * @param batchClassifyDTO 批量分类接收参数实体类
     * @return R
     * @description 接口批量分类
     */
    @Override
    public R<?> batchClassify(BatchClassifyDTO batchClassifyDTO) {
        // 判断批量分类操作的接口中是否存在已发布状态
        LambdaQueryWrapper<ApiDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApiDO::getApiStatus, MyEnumClass.StatusEnum.HAVE_RELEASE.getCode())
                .in(ApiDO::getApiCode, batchClassifyDTO.getApiCodeList());
        int r = apiMapper.selectCount(lambdaQueryWrapper);
        if (r > 0) {
            return R.Failed(ResultCodeEnum.EXIST_HAVE_RELEASE.getCode(), "存在已发布的接口");
        }

        LambdaUpdateWrapper<ApiDO> batchClassifyWrapper = new LambdaUpdateWrapper<>();
        batchClassifyWrapper.in(ApiDO::getApiCode, batchClassifyDTO.getApiCodeList())
                .set(ApiDO::getApiDirectoryCode, batchClassifyDTO.getDirectoryCode());
        int result = apiMapper.update(null,batchClassifyWrapper);
        if (result <= 0) {
            return R.Failed(ResultCodeEnum.OPERATION_FAILED);
        }
        return R.Success(ResultCodeEnum.OPERATION_SUCCESS);
    }

    /**
     * @author 章珑赢
     * @param parameterDTO 查询接口列表参数条件实体类
     * @return R
     * @description 根据接口来源，api状态，接口名称查询接口列表
     **/
    @Override
    public R<?> selectApiListBy(ApiParameterDTO parameterDTO) {
        //分页
        Page<ApiDO>  page = new Page<>(parameterDTO.getPageNum(),parameterDTO.getPageSize());
        LambdaQueryWrapper<ApiDO> apiWrapper = new LambdaQueryWrapper<>();
        //判断code是否传入，根据目录进行查询
        List<String> directoryList = new ArrayList<>();
        if (parameterDTO.getDirectoryCode() != null){
            //根据传入父级目录的Code查出全部子级目录
            directoryList = directoryService.getAllDirectoryCode(parameterDTO.getDirectoryCode(),directoryList);
            //判断其是否为叶子节点,如果为叶子节点将本id传入根据条件进行查询，如果不为叶子节点，将其所有子目录传入
            directoryList.add(parameterDTO.getDirectoryCode());
        }
        //根据接口分类查询
        apiWrapper.in(StringUtils.isNotBlank(parameterDTO.getDirectoryCode()),ApiDO::getApiDirectoryCode,directoryList)
                //根据状态查询
                .eq(StringUtils.isNotBlank(parameterDTO.getApiStatus()),ApiDO::getApiStatus,parameterDTO.getApiStatus())
                //根据接口资源查询
                .eq(StringUtils.isNotBlank(parameterDTO.getApiSource()),ApiDO::getApiSource,parameterDTO.getApiSource())
                //根据接口名称查询
                .like(StringUtils.isNotBlank(parameterDTO.getApiName()),ApiDO::getApiName,parameterDTO.getApiName())
                .orderByAsc(ApiDO::getApiStatus)
                .orderByDesc(ApiDO::getUpdateTime);
        return R.Success(ResultCodeEnum.SUCCESS, apiMapper.selectPage(page,apiWrapper));
    }

    /**
     * @author 邹代鑫
     * @param apiTestDTO 接收测试数据实体类
     * @return R
     * @description 测试接口
     */
    @Override
    public R<?> apiTest(ApiTestDTO apiTestDTO) {
        //判断参数位置,拼接到url和header中
        StringBuilder url = Optional.ofNullable(apiTestDTO.getUrl()).map(StringBuilder::new).orElse(null);
        HttpHeaders header = new HttpHeaders();
        if (apiTestDTO.getInputParams().size() > 0){
           for (InputParam inputParam : apiTestDTO.getInputParams()) {
               //如果input参数位置为query拼接到url中，为header填入header中
               if (MyEnumClass.ApiParamPositionEnum.PARAM_POSITION_QUERY.getCode().equals(inputParam.getApcPosition())) {
                   url = (url == null ? new StringBuilder("null") : url).append("/").append(inputParam.getApcValue());
               }else if (MyEnumClass.ApiParamPositionEnum.PARAM_POSITION_HEADER.getCode().equals(inputParam.getApcPosition())){
                   header.add(inputParam.getApcName(),inputParam.getApcValue());
               }
           }
        }
        //判断是否添加了head
        if (header.size() < 1){
            header.set(String.valueOf(Header.USER_AGENT), DataFactoryConstantPool.HUTOOL_HEADER);
        }
        //判断请求类型
        String result;
        if (MyEnumClass.RequestTypeEnum.REQUEST_METHOD_GET.getCode().equals(apiTestDTO.getApiRequestMethod())) {
            //调用get方法发送请求
            result = HttpRequestUtils.getParameter(header, url, apiTestDTO.getApiRequestTimeout());
        }else if(MyEnumClass.RequestTypeEnum.REQUEST_METHOD_POST.getCode().equals(apiTestDTO.getApiRequestMethod())){
            //调用post方法发送请求
            result = HttpRequestUtils.postBody(header, url, apiTestDTO.getApiRequestTimeout(), apiTestDTO.getBodyParameters());
        }else {
            return R.Failed(ResultCodeEnum.CONNECT_TEST_FAILED);
        }
        return R.Success(ResultCodeEnum.SUCCESS,result);
    }

    /**
     * @author 卑微小峰
     * @param apiCode 接口编号
     * @return R
     * @description 删除未发布接口
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> deleteApi(String apiCode) {
        // 查询此接口编号下的所有含有码值定义的接口配置编号
        List<String> apiParamterConfigurationCodeList = apiParamterConfigurationMapper.getHasStopwatchQuoteApiParamterConfigurationCodeList(apiCode);
        try {
            // 根据接口参数配置编号删除引用
            LambdaQueryWrapper<ApcStopwatchDO> apcStopwatchQueryWrapper = new LambdaQueryWrapper<>();
            if (ObjectUtils.isNotEmpty(apiParamterConfigurationCodeList)) {
                apcStopwatchQueryWrapper.in(ApcStopwatchDO::getApcCode,apiParamterConfigurationCodeList);
                apcStopwatchMapper.delete(apcStopwatchQueryWrapper);

                // 清空该接口下的所有接口参数配置
                LambdaQueryWrapper<ApiParamterConfigurationDO> apcQueryWrapper = new LambdaQueryWrapper<>();
                apcQueryWrapper.eq(ApiParamterConfigurationDO::getApiCode,apiCode);
                apiParamterConfigurationMapper.delete(apcQueryWrapper);
            }
            // 删除此接口
            LambdaQueryWrapper<ApiDO> apiQueryWrapper = new LambdaQueryWrapper<>();
            apiQueryWrapper.eq(ApiDO::getApiCode,apiCode);
            apiMapper.delete(apiQueryWrapper);
        }catch (Exception e){
            return R.Failed(ResultCodeEnum.OPERATION_FAILED);
        }
        return R.Success(ResultCodeEnum.OPERATION_SUCCESS);
    }

    /**
     * @author 卑微小峰
     * @param createOrUpdateApiDTO 需要校验的数据
     * @return R
     * @description 新增/编辑接口数据校验接口
     */
    @Override
    public R<?> verifyApiData(CreateOrUpdateApiDTO createOrUpdateApiDTO) {
        // 判断数据库中是否存在该目录
        LambdaQueryWrapper<DirectoryDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DirectoryDO::getDirectoryCode, createOrUpdateApiDTO.getApiDirectoryCode());
        DirectoryDO directory = directoryMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(directory)) {
            return R.Failed(ResultCodeEnum.OPERATION_FAILED.getCode(), "目录分类不存在", false);
        }
        LambdaQueryWrapper<ApiDO> queryApiWrapper = new LambdaQueryWrapper<>();
        queryApiWrapper.eq(ApiDO::getApiName, createOrUpdateApiDTO.getApiName());
        if (!StringUtils.isBlank(createOrUpdateApiDTO.getApiCode())) {
            // 编辑校验
            queryApiWrapper.ne(ApiDO::getApiCode, createOrUpdateApiDTO.getApiCode());
        }
        // 接口重名校验
        int nameCount = apiMapper.selectCount(queryApiWrapper);
        if (nameCount > 0) {
            return R.Failed(ResultCodeEnum.DATA_EXIST.getCode(), "接口名称已存在", false);
        }

        queryApiWrapper.clear();
        queryApiWrapper.eq(ApiDO::getApiIpPort, createOrUpdateApiDTO.getApiIpPort())
                .eq(ApiDO::getApiPath, createOrUpdateApiDTO.getApiPath());
        if (!StringUtils.isBlank(createOrUpdateApiDTO.getApiCode())) {
            // 编辑校验
            queryApiWrapper.ne(ApiDO::getApiCode, createOrUpdateApiDTO.getApiCode());
        }
        // IP端口+路径重复校验
        int urlCount = apiMapper.selectCount(queryApiWrapper);
        if (urlCount > 0) {
            return R.Failed(ResultCodeEnum.DATA_EXIST.getCode(), "IP:端口/路径已存在", false);
        }
        return R.Success(ResultCodeEnum.SUCCESS, true);
    }


    /**
     * @author 李泓静
     * @param parentCode 父级编号
     * @return List
     * @description 获取所有接口参数配置信息列表
     */
    public List<ApiParamterVO> getApiParamterConfigurationList(String parentCode) {
        List<ApiParamterVO> apiParamterList = new ArrayList<>();
        //接口参数配置wrapper
        LambdaQueryWrapper<ApiParamterConfigurationDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApiParamterConfigurationDO::getApcParentParamCode, parentCode);
        //根据接口Code为父级Code查询所有集合
        List<ApiParamterConfigurationDO> apiParamterConfigurationList = apiParamterConfigurationMapper.selectList(lambdaQueryWrapper);
        if(CollectionUtils.isEmpty(apiParamterConfigurationList)){
            return apiParamterList;
        }
        for (ApiParamterConfigurationDO apiParamterConfiguration : apiParamterConfigurationList) {
            ApiParamterVO createUpdateApiParamter = new ApiParamterVO();
            BeanUtils.copyProperties(apiParamterConfiguration, createUpdateApiParamter);
            apiParamterList.add(createUpdateApiParamter);
        }
        if (apiParamterList.size() > 0) {
            for (ApiParamterVO apiParamter : apiParamterList) {
                apiParamter.setChildren(getApiParamterConfigurationList(apiParamter.getApcCode()));
            }
        }
        return apiParamterList;
    }
}